package dao.fake;

import interfaceDAO.IDAOStation;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import domain.JCDecauxObject;
import domain.JCDecauxQuery;
import domain.Station;

public class FakeDAOStation implements IDAOStation {

	private List<Station> stations = null;

	private synchronized List<Station> loadStations() {
		if (stations == null) {
			stations = new ArrayList<Station>();
			try {
				Map<Integer, JCDecauxObject> map = new JCDecauxQuery()
						.sendRequest();
				for (JCDecauxObject jcDecauxObj : map.values()) {
					stations.add(new Station(jcDecauxObj));
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return stations;
	}

	@Override
	public List<Station> getStationByName(String name) {
		List<Station> ret = new ArrayList<Station>();
		for (Station s : loadStations()) {
			if (s.getName().equals(name)) {
				ret.add(s);
			}
		}
		return ret;
	}

	@Override
	public Station getStationByNumber(int number) {
		for (Station s : loadStations()) {
			if (s.getNumber() == number) {
				return s;
			}
		}
		return null;
	}

	@Override
	public List<Station> getAllStations() {
		return new ArrayList<Station>(loadStations());
	}

	@Override
	public List<Station> getAllStationsBetween(double lat, double lng,
			double latInt, double lngInt) {

		double latMin = (lat - latInt);
		double latMax = (lat + latInt);
		double lngMin = (lng - lngInt);
		double lngMax = (lng + lngInt);

		List<Station> ret = new ArrayList<Station>();
		for (Station s : loadStations()) {
			if (s.getLatitude() >= latMin && s.getLatitude() <= latMax
					&& s.getLongitude() >= lngMin && s.getLongitude() <= lngMax) {
				ret.add(s);
			}
		}

		return ret;
	}

}
